import React, { useState, useRef, useEffect } from 'react';
import { 
  View, Text, TouchableOpacity, StyleSheet, 
  Image, FlatList, Dimensions, ImageSourcePropType,
  TextInput, StatusBar
} from 'react-native';
import PagerView from 'react-native-pager-view';

// 定义类型
interface Tab {
  name: string;
  key: string;
}

interface Product {
  id: string;
  name: string;
  price: string;
  image: string;
}

interface Banner {
  id: string;
  image: ImageSourcePropType;
  title: string;
}

interface Message {
  id: string;
  userId: string;
  userName: string;
  userAvatar: string;
  content: string;
  time: string;
  unread: boolean;
}

// 屏幕宽度和状态栏高度
const { width } = Dimensions.get('window');
const STATUS_BAR_HEIGHT = StatusBar.currentHeight || 24; // 获取状态栏高度，默认24
const BANNER_INTERVAL = 3000; // 轮播间隔时间(毫秒)

const App = () => {
  // 标签页数据 - 中间为消息
  const tabs: Tab[] = [
    { name: '首页000', key: 'home' },
    { name: '消息', key: 'message' },
    { name: '我的', key: 'profile' }
  ];

  // 轮播Banner数据
  const banners: Banner[] = [
    {
      id: 'b1',
      image: { uri: 'https://picsum.photos/seed/banner1/600/200' },
      title: '夏季大促销----'
    },
    {
      id: 'b2',
      image: { uri: 'https://picsum.photos/seed/banner2/600/200' },
      title: '新品上市'
    },
    {
      id: 'b3',
      image: { uri: 'https://picsum.photos/seed/banner3/600/200' },
      title: '限时折扣'
    }
  ];

  // 模拟商品数据
  const [products, setProducts] = useState<Product[]>([]);
  
  // 消息数据
  const [messages, setMessages] = useState<Message[]>([]);
  
  // 当前页索引
  const [index, setIndex] = useState<number>(0);
  // 当前Banner索引
  const [bannerIndex, setBannerIndex] = useState<number>(0);
  // PagerView引用
  const pagerRef = useRef<PagerView>(null);
  // Banner PagerView引用
  const bannerPagerRef = useRef<PagerView>(null);
  // 定时器引用
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // 设置状态栏样式 - 文字为黑色
  useEffect(() => {
    // 设置状态栏文字颜色为黑色
    StatusBar.setBarStyle('dark-content');
    // 对于Android，设置状态栏背景透明（可选）
    StatusBar.setTranslucent(true);
    
    return () => {
      // 组件卸载时恢复默认设置（可选）
      StatusBar.setBarStyle('default');
    };
  }, []);

  // 初始化商品和消息数据
  useEffect(() => {
    // 初始化商品数据
    const mockProducts: Product[] = Array.from({ length: 10 }, (_, i) => ({
      id: `p${i}`,
      name: `商品 ${i + 1}`,
      price: `¥${(99 + i * 30).toFixed(2)}`,
      image: `https://picsum.photos/seed/product${i}/300/300`
    }));
    setProducts(mockProducts);

    // 初始化消息数据
    const mockMessages: Message[] = [
      {
        id: 'm1',
        userId: 'u1',
        userName: '张三',
        userAvatar: 'https://picsum.photos/seed/user1/100/100',
        content: '你好，这个商品还有货吗？',
        time: '09:45',
        unread: true
      },
      {
        id: 'm2',
        userId: 'u2',
        userName: '李四',
        userAvatar: 'https://picsum.photos/seed/user2/100/100',
        content: '订单已经发货了，请注意查收',
        time: '昨天',
        unread: false
      },
      {
        id: 'm3',
        userId: 'u3',
        userName: '客服中心',
        userAvatar: 'https://picsum.photos/seed/service/100/100',
        content: '您的优惠券即将过期，请尽快使用',
        time: '07-20',
        unread: true
      },
      {
        id: 'm4',
        userId: 'u4',
        userName: '王五',
        userAvatar: 'https://picsum.photos/seed/user4/100/100',
        content: '周末有空一起打球吗？',
        time: '07-18',
        unread: false
      }
    ];
    setMessages(mockMessages);
  }, []);

  // 初始化Banner自动轮播
  useEffect(() => {
    startBannerTimer();
    
    // 组件卸载时清除定时器
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  // 开始Banner轮播定时器
  const startBannerTimer = () => {
    // 清除已有定时器
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    
    // 设置新定时器
    timerRef.current = setInterval(() => {
      // 计算下一个Banner索引，循环播放
      const nextIndex = (bannerIndex + 1) % banners.length;
      setBannerIndex(nextIndex);
      bannerPagerRef.current?.setPage(nextIndex, true); // 带动画切换
    }, BANNER_INTERVAL);
  };

  // 处理Banner手动滑动
  const handleBannerPageSelected = (e: { nativeEvent: { position: number } }) => {
    const newIndex = e.nativeEvent.position;
    setBannerIndex(newIndex);
    
    // 手动滑动后重置定时器
    startBannerTimer();
  };

  // 切换页面
  const goToPage = (pageIndex: number) => {
    setIndex(pageIndex);
    pagerRef.current?.setPage(pageIndex);
  };

  // 处理页面选中事件
  const handlePageSelected = (e: { nativeEvent: { position: number } }) => {
    setIndex(e.nativeEvent.position);
  };

  // 渲染Banner指示器（居中显示）
  const renderBannerIndicators = () => {
    return (
      <View style={styles.indicatorsContainer}>
        {banners.map((_, i) => (
          <View
            key={i}
            style={[
              styles.indicator,
              i === bannerIndex && styles.activeIndicator
            ]}
          />
        ))}
      </View>
    );
  };

  // 渲染消息列表项
  const renderMessageItem = ({ item }: { item: Message }) => {
    return (
      <View style={styles.messageItem}>
        <Image
          source={{ uri: item.userAvatar }}
          style={styles.avatar}
          alt={item.userName}
        />
        <View style={styles.messageContent}>
          <View style={styles.messageHeader}>
            <Text style={styles.userName}>{item.userName}</Text>
            <Text style={styles.messageTime}>{item.time}</Text>
          </View>
          <Text style={styles.messageText} numberOfLines={1}>
            {item.content}
          </Text>
        </View>
        {item.unread && (
          <View style={styles.unreadDot} />
        )}
      </View>
    );
  };

  // 首页内容
  const renderHomePage = () => (
    <View style={styles.homeContainer}>
      {/* 自动轮播Banner */}
      <View style={styles.bannerContainer}>
        <PagerView
          ref={bannerPagerRef}
          style={styles.bannerPager}
          initialPage={0}
          onPageSelected={handleBannerPageSelected}
          scrollEnabled={true}
        >
          {banners.map((banner) => (
            <View key={banner.id} style={styles.bannerItem}>
              <Image
                source={banner.image}
                style={styles.bannerImage}
                alt={banner.title}
              />
              <Text style={styles.bannerText}>{banner.title}</Text>
            </View>
          ))}
        </PagerView>
        
        {/* Banner指示器 - 居中显示 */}
        {renderBannerIndicators()}
      </View>

      {/* 列表标题 */}
      <Text style={styles.listTitle}>推荐商品</Text>

      {/* 商品列表 */}
      <FlatList
        data={products}
        renderItem={({ item }) => (
          <View style={styles.productItem}>
            <Image
              source={{ uri: item.image }}
              style={styles.productImage}
              alt={item.name}
            />
            <View style={styles.productInfo}>
              <Text style={styles.productName}>{item.name}</Text>
              <Text style={styles.productPrice}>{item.price}</Text>
            </View>
          </View>
        )}
        keyExtractor={item => item.id}
        showsVerticalScrollIndicator={false}
      />
    </View>
  );

  // 消息页面内容
  const renderMessagePage = () => (
    <View style={styles.messageContainer}>
      {/* 状态栏占位 */}
      <View style={styles.statusBarPlaceholder} />
      
      {/* 搜索框 */}
      <View style={styles.searchBar}>
        <TextInput
          style={styles.searchInput}
          placeholder="搜索消息..."
          placeholderTextColor="#999"
        />
      </View>
      
      {/* 消息列表 */}
      <FlatList
        data={messages}
        renderItem={renderMessageItem}
        keyExtractor={item => item.id}
        showsVerticalScrollIndicator={false}
        ListHeaderComponent={
          messages.length === 0 ? (
            <View style={styles.emptyState}>
              <Text style={styles.emptyText}>暂无消息</Text>
            </View>
          ) : null
        }
      />
    </View>
  );

  // 我的页面内容
  const renderProfilePage = () => (
    <View style={styles.profileContainer}>
      {/* 状态栏占位 */}
      <View style={styles.statusBarPlaceholder} />
      
      <View style={styles.profileHeader}>
        <Image
          source={{ uri: 'https://picsum.photos/seed/user/100/100' }}
          style={styles.avatar}
          alt="用户头像"
        />
        <View style={styles.userInfo}>
          <Text style={styles.userName}>用户名</Text>
          <Text style={styles.userStatus}>普通会员</Text>
        </View>
      </View>
      
      <View style={styles.profileMenu}>
        <TouchableOpacity style={styles.menuItem}>
          <Text style={styles.menuText}>我的订单</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.menuItem}>
          <Text style={styles.menuText}>收藏夹</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.menuItem}>
          <Text style={styles.menuText}>设置</Text>
        </TouchableOpacity>
      </View>
    </View>
  );

  return (
    <View style={styles.container}>
      {/* 页面内容 */}
      <PagerView
        ref={pagerRef}
        style={styles.pager}
        onPageSelected={handlePageSelected}
      >
        <View key={tabs[0].key}>{renderHomePage()}</View>
        <View key={tabs[1].key}>{renderMessagePage()}</View>
        <View key={tabs[2].key}>{renderProfilePage()}</View>
      </PagerView>

      {/* 底部导航 */}
      <View style={styles.tabs}>
        {tabs.map((tab, i) => (
          <TouchableOpacity
            key={tab.key}
            style={styles.tab}
            onPress={() => goToPage(i)}
          >
            <Text style={[styles.tabText, index === i && styles.activeText]}>
              {tab.name}
            </Text>
          </TouchableOpacity>
        ))}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  pager: {
    flex: 1,
  },
  
  // 状态栏占位组件样式
  statusBarPlaceholder: {
    height: STATUS_BAR_HEIGHT,
    backgroundColor: '#f5f5f5', // 与页面背景色一致
  },
  
  // 首页样式
  homeContainer: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  bannerContainer: {
    width: width,
    height: 180,
    position: 'relative',
  },
  bannerPager: {
    width: '100%',
    height: '100%',
  },
  bannerItem: {
    width: '100%',
    height: '100%',
    position: 'relative',
  },
  bannerImage: {
    width: '100%',
    height: '100%',
    resizeMode: 'cover',
  },
  bannerText: {
    position: 'absolute',
    bottom: 16,
    left: 16,
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
    textShadowColor: 'rgba(0, 0, 0, 0.5)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  indicatorsContainer: {
    position: 'absolute',
    bottom: 10,
    left: 0,
    right: 0,
    flexDirection: 'row',
    gap: 6,
    justifyContent: 'center',
    alignItems: 'center',
  },
  indicator: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
  activeIndicator: {
    backgroundColor: '#fff',
    width: 24,
  },
  
  listTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    padding: 16,
    backgroundColor: '#fff',
  },
  productItem: {
    flexDirection: 'row',
    padding: 16,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  productImage: {
    width: 80,
    height: 80,
    borderRadius: 8,
    resizeMode: 'cover',
  },
  productInfo: {
    marginLeft: 16,
    justifyContent: 'center',
    flex: 1,
  },
  productName: {
    fontSize: 16,
    marginBottom: 8,
  },
  productPrice: {
    fontSize: 16,
    color: '#ff4d4f',
    fontWeight: 'bold',
  },
  
  // 消息页面样式
  messageContainer: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  searchBar: {
    padding: 10,
    backgroundColor: '#f5f5f5',
  },
  searchInput: {
    height: 40,
    backgroundColor: '#fff',
    borderRadius: 20,
    paddingHorizontal: 16,
    fontSize: 14,
  },
  messageItem: {
    flexDirection: 'row',
    padding: 12,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    alignItems: 'center',
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
  },
  messageContent: {
    flex: 1,
    marginLeft: 12,
    marginRight: 12,
  },
  messageHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 4,
  },
  userName: {
    fontSize: 16,
    fontWeight: '500',
  },
  messageTime: {
    fontSize: 12,
    color: '#999',
  },
  messageText: {
    fontSize: 14,
    color: '#666',
  },
  unreadDot: {
    width: 10,
    height: 10,
    borderRadius: 5,
    backgroundColor: '#ff4d4f',
  },
  emptyState: {
    padding: 40,
    alignItems: 'center',
  },
  emptyText: {
    color: '#999',
    fontSize: 16,
  },
  
  // 我的页面样式
  profileContainer: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  profileHeader: {
    backgroundColor: '#fff',
    padding: 20,
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  userInfo: {
    marginLeft: 16,
  },
  userStatus: {
    fontSize: 14,
    color: '#666',
  },
  profileMenu: {
    marginTop: 16,
  },
  menuItem: {
    backgroundColor: '#fff',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  menuText: {
    fontSize: 16,
  },
  
  // 底部导航样式
  tabs: {
    flexDirection: 'row',
    height: 50,
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  tab: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  tabText: {
    fontSize: 16,
    color: '#666',
  },
  activeText: {
    color: '#007AFF',
    fontWeight: 'bold',
  },
});

export default App;